const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const htmlWebpackPlugin = require('html-webpack-plugin');
const extractTextPlugin = require('extract-text-webpack-plugin');

/**
 * 删除文件夹
 * @param {*} path
 */
function deleteFolder(path) {
	var files = [];
	if (fs.existsSync(path)) {
		files = fs.readdirSync(path);
		files.forEach(function(file, index) {
			var curPath = path + '/' + file;
			if (fs.statSync(curPath).isDirectory()) {
				deleteFolder(curPath);
			} else {
				fs.unlinkSync(curPath);
			}
		});
		fs.rmdirSync(path);
	}
}

let config = {
	entry: {
		//【改动1】
		index: './view/index/index.js', //index入口
		login: './view/login/login.js', //login入口
	},
	output: {
		path: path.resolve(__dirname, '../dist'),
		filename: '[name]/[name].[hash].js', //【改动2】
	},
	plugins: [
		new extractTextPlugin('[name]/[name].[hash].css'), //抽离css 如:index/index.123456.css 【你不一定用得上】
		new htmlWebpackPlugin({
			template: './view/index/index.html', //模板位置
			filename: 'index/index.html', //生成位置【改动4】
			chunks: ['index'], //对应的入口【改动5】
		}),
		new htmlWebpackPlugin({
			template: './view/login/login.html', //模板位置
			filename: 'login/login.html', //生成位置【改动4】
			chunks: ['login'], //对应的入口【改动5】
		}),
	],
	module: {
		rules: [
			{
				test: /\.css$/, //匹配css文件
				use: extractTextPlugin.extract({
					//抽离css
					fallback: 'style-loader',
					use: 'css-loader',
				}),
			},
		],
	},
	mode: 'production',
};

// 构建前先删除文件
deleteFolder(config.output.path);

// 没有全局安装webpack需要修改下面，并修改build命令为node .\config\prod.config.js
// webpack(config, (err, status) => {});

// 已全局安装webpack
module.exports = config;
